package com.iqiju.guagua.redtone.video.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iqiju.guagua.redtone.video.mapper.WxMiniAppMapper;
import com.iqiju.guagua.redtone.video.model.WxMiniApp;
import com.iqiju.guagua.redtone.video.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Slf4j
@Service
public class WxMiniAppService extends ServiceImpl<WxMiniAppMapper, WxMiniApp> {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /** 查询小程序信息 */
    public WxMiniApp selectById(long id){
        String key = getWxMiniAppKey(String.valueOf(id));
        String appValue = stringRedisTemplate.opsForValue().get(key);
        WxMiniApp wxMiniApp = null;
        if (StringUtils.isNotNull(appValue)){
            wxMiniApp = JSON.parseObject(appValue, WxMiniApp.class);
            return wxMiniApp;
        }
        wxMiniApp = getById(id);
        if (wxMiniApp==null){
            return null;
        }
        stringRedisTemplate.opsForValue().set(key,JSON.toJSONString(wxMiniApp),30, TimeUnit.DAYS);
        return wxMiniApp;
    }

    private String getWxMiniAppKey(String id){
        return "IQIJU_WX_MINI_APP_"+id;
    }

    public void delWxMiniAppKey(String id){
        stringRedisTemplate.delete(getWxMiniAppKey(id));
    }
}
